﻿using BestHTTP;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VoiceRecognition : MonoBehaviour
{
    List<GameObject> resultGos = new List<GameObject>();

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void Register(GameObject go)
    {
        bool got = false;
        for (int i = 0; i < resultGos.Count; i++)
            if (resultGos[i] == go)
                got = true;
        if (!got)
            resultGos.Add(go);
    }

    public void Unregister(GameObject go)
    {
        for (int i = 0; i < resultGos.Count; i++)
            if (resultGos[i] == go)
            {
                resultGos.RemoveAt(i);
                break;
            }
    }

    public void OnVoiceRecordBytes(byte[] bytes)
    {
        byte[] bytes2 = new byte[bytes.Length];
        Buffer.BlockCopy(bytes, 0, bytes2, 0, bytes.Length);

        var request = new HTTPRequest(new Uri("https://ilab.chu-jiao.com:8069/Interface/speech"), HTTPMethods.Post, onFinished);
        request.AddBinaryData("file", bytes2, "file.wav");
        request.AddField("rate", "8000");
        request.AddField("format", "pcm");
        request.Send();
    }

    private void onFinished(HTTPRequest originalRequest, HTTPResponse response)
    {
        if (response != null)
        {
            if (response.IsSuccess == false)
            {
                print("Recognize() failed.");
                return;
            }

            string[] strs = parseResult(response.DataAsText);
            if (strs[0] == "success.")
                foreach (GameObject go in resultGos)
                    go.SendMessage("OnVoiceResult", strs[1], SendMessageOptions.DontRequireReceiver);
        }
        else
        {
            print("Recognize() failed, no response.");
        }
    }

    string[] parseResult(string str)
    {
//        print("parsing:" + str);
        if (str[0] == '{')
            str = str.Substring(1);
        if (str[str.Length - 1] == '}')
            str = str.Substring(0, str.Length - 1);
        string[] strs = str.Split(',');

        string[] ss = new string[2];
        for (int i = 0; i < strs.Length; i++)
        {
            string[] tmp = strs[i].Split(':');
            if (tmp[0] == "\"err_msg\"")
                ss[0] = tmp[1].Substring(1, tmp[1].Length - 2);
            if (tmp[0] == "\"result\"")
                ss[1] = tmp[1].Substring(2, tmp[1].Length - 4);
        }

        return ss;
    }
}
